import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  InputNumber, 
  message, 
  Typography, 
  Space, 
  Card, 
  Image, 
  Popconfirm,
  Empty,
  Divider,
  Row,
  Col
} from 'antd';
import { 
  DeleteOutlined, 
  ShoppingOutlined,
  ClearOutlined,
  ArrowLeftOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { cartApi, orderApi } from '../../api';

const { Title, Text } = Typography;

const Cart = () => {
  const [loading, setLoading] = useState(false);
  const [cartItems, setCartItems] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [creating, setCreating] = useState(false);
  
  const navigate = useNavigate();

  // 获取购物车
  const fetchCart = async () => {
    setLoading(true);
    try {
      const response = await cartApi.getCart();
      if (response.success) {
        const items = response.data || [];
        setCartItems(items);
        // 默认选中所有有库存的商品
        const availableKeys = items
          .filter(item => item.book && item.book.stock > 0)
          .map(item => item.id);
        setSelectedRowKeys(availableKeys);
      } else {
        message.error(response.message || '获取购物车失败');
      }
    } catch (error) {
      console.error('获取购物车错误:', error);
      message.error('获取购物车失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCart();
  }, []);

  // 更新商品数量
  const updateQuantity = async (bookId, quantity) => {
    if (quantity < 1) return;
    
    try {
      const response = await cartApi.updateCartItem(bookId, quantity);
      if (response.success) {
        fetchCart(); // 重新获取购物车
      } else {
        message.error(response.message || '更新数量失败');
      }
    } catch (error) {
      console.error('更新数量错误:', error);
      message.error('更新数量失败');
    }
  };

  // 删除商品
  const removeItem = async (bookId) => {
    try {
      const response = await cartApi.removeFromCart(bookId);
      if (response.success) {
        message.success('已从购物车移除');
        fetchCart(); // 重新获取购物车
      } else {
        message.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除商品错误:', error);
      message.error('删除失败');
    }
  };

  // 清空购物车
  const clearCart = async () => {
    try {
      const response = await cartApi.clearCart();
      if (response.success) {
        message.success('购物车已清空');
        setCartItems([]);
        setSelectedRowKeys([]);
      } else {
        message.error(response.message || '清空购物车失败');
      }
    } catch (error) {
      console.error('清空购物车错误:', error);
      message.error('清空购物车失败');
    }
  };

  // 创建订单
  const createOrder = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要结算的商品');
      return;
    }

    setCreating(true);
    try {
      const response = await orderApi.createOrder();
      if (response.success) {
        message.success('订单创建成功');
        navigate('/orders');
      } else {
        message.error(response.message || '创建订单失败');
      }
    } catch (error) {
      console.error('创建订单错误:', error);
      message.error('创建订单失败');
    } finally {
      setCreating(false);
    }
  };

  // 计算总价
  const calculateTotal = () => {
    return cartItems
      .filter(item => selectedRowKeys.includes(item.id))
      .reduce((total, item) => {
        return total + (item.book?.price || 0) * item.quantity;
      }, 0);
  };

  // 表格列定义
  const columns = [
    {
      title: '商品信息',
      dataIndex: 'book',
      key: 'book',
      width: '40%',
      render: (book) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Image
            src={book?.cover}
            alt={book?.name}
            width={60}
            height={80}
            style={{ marginRight: 12 }}
            fallback=""
            preview={false}
          />
          <div>
            <div style={{ fontWeight: 'bold', marginBottom: 4 }}>
              {book?.name}
            </div>
            <div style={{ color: '#666', fontSize: '12px' }}>
              作者: {book?.author}
            </div>
            <div style={{ color: '#666', fontSize: '12px' }}>
              出版社: {book?.publisher}
            </div>
          </div>
        </div>
      )
    },
    {
      title: '单价',
      dataIndex: ['book', 'price'],
      key: 'price',
      width: '15%',
      render: (price) => (
        <Text strong style={{ color: '#ff4d4f' }}>
          ¥{price?.toFixed(2)}
        </Text>
      )
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
      width: '15%',
      render: (quantity, record) => (
        <InputNumber
          min={1}
          max={record.book?.stock || 999}
          value={quantity}
          onChange={(value) => updateQuantity(record.bookId, value)}
          size="small"
        />
      )
    },
    {
      title: '库存',
      dataIndex: ['book', 'stock'],
      key: 'stock',
      width: '10%',
      render: (stock) => (
        <Text type={stock > 0 ? 'success' : 'danger'}>
          {stock > 0 ? stock : '缺货'}
        </Text>
      )
    },
    {
      title: '小计',
      key: 'subtotal',
      width: '15%',
      render: (_, record) => (
        <Text strong style={{ color: '#ff4d4f' }}>
          ¥{((record.book?.price || 0) * record.quantity).toFixed(2)}
        </Text>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: '10%',
      render: (_, record) => (
        <Popconfirm
          title="确定要删除这个商品吗？"
          onConfirm={() => removeItem(record.bookId)}
          okText="确定"
          cancelText="取消"
        >
          <Button 
            type="text" 
            danger 
            icon={<DeleteOutlined />}
            size="small"
          >
            删除
          </Button>
        </Popconfirm>
      )
    }
  ];

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
    getCheckboxProps: (record) => ({
      disabled: !record.book || record.book.stock === 0,
    }),
  };

  if (cartItems.length === 0 && !loading) {
    return (
      <div>
        <Button 
          icon={<ArrowLeftOutlined />} 
          onClick={() => navigate('/books')}
          style={{ marginBottom: 16 }}
        >
          继续购物
        </Button>
        
        <Card>
          <Empty
            description="购物车是空的"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          >
            <Button type="primary" onClick={() => navigate('/books')}>
              去购物
            </Button>
          </Empty>
        </Card>
      </div>
    );
  }

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Space>
          <Button 
            icon={<ArrowLeftOutlined />} 
            onClick={() => navigate('/books')}
          >
            继续购物
          </Button>
          
          <Title level={2} style={{ margin: 0 }}>
            购物车
          </Title>
        </Space>
      </div>

      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Text>
              共 {cartItems.length} 件商品，已选择 {selectedRowKeys.length} 件
            </Text>
            
            {cartItems.length > 0 && (
              <Popconfirm
                title="确定要清空购物车吗？"
                onConfirm={clearCart}
                okText="确定"
                cancelText="取消"
              >
                <Button 
                  type="text" 
                  danger 
                  icon={<ClearOutlined />}
                  size="small"
                >
                  清空购物车
                </Button>
              </Popconfirm>
            )}
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={cartItems}
          rowKey="id"
          loading={loading}
          rowSelection={rowSelection}
          pagination={false}
          scroll={{ x: 800 }}
        />

        <Divider />

        <Row justify="end">
          <Col>
            <Space size="large" align="center">
              <div>
                <Text>合计: </Text>
                <Text 
                  style={{ 
                    fontSize: '20px', 
                    fontWeight: 'bold', 
                    color: '#ff4d4f' 
                  }}
                >
                  ¥{calculateTotal().toFixed(2)}
                </Text>
              </div>
              
              <Button
                type="primary"
                size="large"
                icon={<ShoppingOutlined />}
                loading={creating}
                disabled={selectedRowKeys.length === 0}
                onClick={createOrder}
              >
                结算 ({selectedRowKeys.length})
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default Cart; 